package com.kcyu.sfherp.service;

import com.kcyu.sfherp.dto.LocalFileDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Date;

@Slf4j
@Service
public class FileServer {

    // 获取临时目录
    public String getTempDir() {
        return System.getProperty("java.io.tmpdir");
    }

    // 获取项目目录
    public String getProjectDir() {
        return System.getProperty("user.dir");
    }

    // 获取系统运行环境
    public String getSystemEnv() {
        return System.getProperty("os.name");
    }

    // 生成文件路径
    public LocalFileDTO generateFilePath(String fileName, String suffix) {
        // 如果没有目录，先创建
        String fileName1 =  fileName + new Date().getTime() + suffix;
        File file = new File(this.getTempDir() + fileName1);
        if(this.getSystemEnv().toLowerCase().contains("windows")) {
            // 如果是windows系统，路径为项目目录
            file = new File(this.getTempDir() + fileName1);
        } else {
            file = new File(this.getTempDir() + "/" + fileName1);
        }
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }else{
                file.delete();
                file.createNewFile();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        LocalFileDTO localFileDTO = new LocalFileDTO();
        localFileDTO.setFileName(fileName1);
        localFileDTO.setPath(file.getPath());
        localFileDTO.setDownloadPath("/download/temp?fileName=" + fileName1);
        return localFileDTO;
    }

    // 获取当前执行环境
    public String getEnv() {
        return System.getProperty("spring.profiles.active");
    }

    // 从临时目录下载文件
    public String downloadFromTempDir(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {
        // 去临时目录找文件
        File file = new File(this.getTempDir() + fileName);
        if(getSystemEnv().toLowerCase().contains("windows")) {
            // 如果是windows系统，路径为项目目录
            file = new File(this.getTempDir() + fileName);
        } else {
            file = new File(this.getTempDir() + "/" + fileName);
        }
        log.info("下载文件路径：" + file.getAbsolutePath());
        if (!file.exists()) {
            return "文件不存在";
        }
        //使用URLEncoder解决中文变__问题
        //response.setHeader("Content-Disposition", "attachment;fileName=" + filePathName);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));
        try {
            InputStream inStream = Files.newInputStream(file.toPath());
            OutputStream os = response.getOutputStream();
            byte[] buff = new byte[1024];
            int i = 0;
            //read方法返回读取到字节数，=0说明到达文件结尾，=-1说明发生错误
            while ((i = inStream.read(buff)) != -1) {
                //write()方法3个参数，可自定义读取字节数0-i;
                os.write(buff, 0, i);
            }
            os.flush();
            os.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "下载成功";
    }

}
